import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { Table, Pagination, ConfigProvider } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import zhCN from 'antd/es/locale/zh_CN';
import './index.css';

interface baseBankTableProps {
  columns: ColumnsType<DataType>;
  data: DataType[];
  tableType?: 'checkbox' | 'radio',
  paginationInfo: paginationInfoProps;
  callbackSearchItem?: (page: number, pageSize: number) => void;
  callbackSetSelectedRowKeys?: (arr: React.Key[]) => void;
}

const BankTable = forwardRef((props: baseBankTableProps, _ref) => {
  const { columns, data, callbackSearchItem, callbackSetSelectedRowKeys, paginationInfo: { total }, tableType = "checkbox" } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [pageSize, setPageSize] = useState(10);
  const [page, setPage] = useState(1);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    if (callbackSetSelectedRowKeys) {
      callbackSetSelectedRowKeys(newSelectedRowKeys);
    }
  };

  const rowSelection = { type: tableType, selectedRowKeys, onChange: onSelectChange };

  const handlePaginationOnchange = (page: number, pageSize: number) => {
    setPageSize(pageSize);
    setPage(page);
    if (callbackSearchItem) {
      callbackSearchItem(page, pageSize);
    }
  }

  useImperativeHandle(_ref, () => {
    const selectItemList = data.filter(k => selectedRowKeys.includes(k.key));
    return {
      selectedRowKeys,
      selectedRowKeysItem: selectItemList
    }
  })

  return (
    <>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        pagination={false}
        rowKey={(k, i) => k.key.toString()}
      />
      <div className='pagination'>
        <ConfigProvider locale={zhCN}>
          <Pagination
            total={total}
            showSizeChanger
            showQuickJumper
            pageSize={pageSize}
            current={page}
            onChange={handlePaginationOnchange}
            showTotal={(total) => `总 ${total} 条数 `}
          />
        </ConfigProvider>
      </div>
    </>
  )
})

export { BankTable };